package com.spic.business.common.utils;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.spic.common.security.utils.cache.UserCacheUtils;
import com.spic.system.api.dto.UserDTO;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;

import java.util.Map;

import static java.util.stream.Collectors.toMap;

@Getter
@Setter
@EqualsAndHashCode
public class UserCodeConverter implements Converter<String> {
    //缓存Map<id,name>
    private Map<Long, String> userMap = UserCacheUtils.getCache().stream().collect(toMap(UserDTO::getUserId, UserDTO::getNickName));

    @Override
    public Class<?> supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    /**
     * 这里读的时候会调用
     *
     * @param context
     * @return
     */
    @Override
    public String convertToJavaData(ReadConverterContext<?> context) {
        return context.getReadCellData().getStringValue();
    }

    /**
     * 这里是写的时候会调用
     *
     * @return
     */
    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<String> context) {
        return new WriteCellData<>(userMap.get(Long.parseLong(context.getValue())));
    }
}
